﻿using Microsoft.Extensions.Logging;
using System;
using WHLRDF.Log;

namespace WHLRDF.ORM.EF
{
    public class EFLogger : ILogger
    {
        private readonly string categoryName;

        public EFLogger(string categoryName) => this.categoryName = categoryName;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            //ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
            if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command"
                    && logLevel == LogLevel.Information)
            {
                var logContent = formatter(state, exception);
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\(([0-9]([\\.0-9]+)?)ms\\)");
                var match = regex.Match(logContent);
                double tickTimes = 0;
                if (match.Success)
                {
                    tickTimes = Convert.ToDouble(match.Groups[1].Value.ToString().Trim());
                }
             
                LogHelper.SQLInfo(logContent, tickTimes, "EF",ApplicationEnvironments.ProviderType.ToString());
            }
        }

        public IDisposable BeginScope<TState>(TState state) => null;
    }
    /// <summary>
    /// ILoggerProvider实现类
    /// </summary>
    public class EFLoggerProvider : ILoggerProvider
    {
        public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName);
        public void Dispose() { }
    }
}
